package com.wwtech.epp.ui.activity.friend;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.socks.library.KLog;
import com.wwtech.epp.R;
import com.wwtech.epp.application.AppConfig;
import com.wwtech.epp.base.BaseActivity;
import com.wwtech.epp.contain.ContainValue;
import com.wwtech.epp.db.Friend;
import com.wwtech.epp.entity.multi.PersonItem;
import com.wwtech.epp.ui.activity.friend.component.DaggerAddPersonComponent;
import com.wwtech.epp.ui.activity.friend.contract.AddPersonContract;
import com.wwtech.epp.ui.activity.friend.module.AddPersonModule;
import com.wwtech.epp.ui.activity.friend.presenter.AddPersonPresenter;
import com.wwtech.epp.ui.adapter.main.CheckPersonAdapter;
import com.wwtech.epp.ui.adapter.main.GroupMemberAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.wwtech.epp.ui.adapter.main.CheckPersonAdapter.TYPE_PERSON;

/**
 * @author hzp
 * @Package com.wwtech.epp.ui.activity.friend
 * @Description: $description   选择添加人员的界面
 * @date 2017/09/12 23:05:17
 */

public class AddPersonActivity extends BaseActivity implements AddPersonContract.View, CheckPersonAdapter.OnItemClickListenerme, GroupMemberAdapter.OnCheckChange, CheckPersonAdapter.OnPersonCheckChange {

    @Inject
    AddPersonPresenter mPresenter;
    @Inject
    CheckPersonAdapter checkPersonAdapter;

    GroupMemberAdapter groupMemberAdapter;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.recycerView_jiagou)
    RecyclerView recycerViewJiagou;
    @BindView(R.id.jiagou)
    RelativeLayout jiagou;
    @BindView(R.id.bottom)
    LinearLayout bottom;
    @BindView(R.id.tv_count)
    TextView tvCount;
    private ArrayList<Friend> tempCheckedFriend = new ArrayList<>();

    private ArrayList<Friend> currentAdapterList;

    private boolean canDelet = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_add_person);
        ButterKnife.bind(this);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        checkPersonAdapter.isSingleChoose = false;
        checkPersonAdapter.setOncheckChange(this);
        if (getIntent().getStringExtra("title").equals("添加群成员")) {
            checkPersonAdapter.setCanDelet(false);
        }
        if (getIntent().getStringExtra("title").equals("发起群聊")) {
            checkPersonAdapter.setCanDelet(false);
        }
        for (int i = 0; i < ContainValue.userList.size(); i++) {
            if (ContainValue.userList.get(i).getItemType() == CheckPersonAdapter.TYPE_PERSON) {
                final PersonItem lv1 = (PersonItem) ContainValue.userList.get(i);
                if (lv1.type.equals("contact")) {
                    KLog.i("清除以前的数据");
                    ((PersonItem) ContainValue.userList.get(i)).freind.setChecked(true);
                    ((PersonItem) ContainValue.userList.get(i)).freind.setCanCheck(true);
                }

                //如果是添加群成员的多选操作，在这里初始化已经在群组里的好友
                if (getIntent().getStringExtra("title").equals("添加群成员")) {
                    for (int j = 0; j < ContainValue.currentGroupMember.size(); j++) {
                        if ("contact".equals(lv1.type)) {
                            if (ContainValue.currentGroupMember.get(j).getUserId().equals(lv1.freind.getUserId())) {
                                ((PersonItem) ContainValue.userList.get(i)).freind.setCanCheck(false);
                            }
                        }
                    }
                }
                //如果是发起群聊，在这里处理发起人本身在群中
                if (getIntent().getStringExtra("title").equals("发起群聊")) {
                    if ("contact".equals(lv1.type)) {
                        if ((ContainValue.userLogin.getData().getUserId() + "").equals(lv1.freind.getUserId())) {
                            ((PersonItem) ContainValue.userList.get(i)).freind.setCanCheck(false);
                        }
                    }
                }
            }
        }

        checkPersonAdapter.setNewData(ContainValue.userList);
        recyclerView.setAdapter(checkPersonAdapter);
        checkPersonAdapter.setOnItemClick(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.all_select, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.all_select:
                for (int i = 0; i < currentAdapterList.size(); i++) {
                    if (getIntent().getStringExtra("title").equals("添加群成员") && !currentAdapterList.get(i).isCanCheck()) {
                        continue;
                    }
                    if (getIntent().getStringExtra("title").equals("发起群聊") && !currentAdapterList.get(i).isCanCheck()) {
                        continue;
                    }
                    currentAdapterList.get(i).setChecked(true);
                    mPresenter.onCheckChange(currentAdapterList.get(i), true);
                }
                groupMemberAdapter.notifyDataSetChanged();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void initData() {
        if (getIntent().getStringExtra("title").equals("添加群成员") || "发起群聊".equals(getIntent().getStringExtra("title"))) {
            canDelet = false;
            mPresenter.setCanDelet(false);
        }
        mPresenter.setType(getIntent().getStringExtra("title"));
        setTitle(getIntent().getStringExtra("title"));
        if ((ContainValue.partPerson == null || ContainValue.partPerson.size() == 0)) {
            Friend tempFriend = new Friend("", "-1", "", Uri.parse(""));
            tempFriend.setUserId("-1");
            ContainValue.partPerson = new ArrayList<Friend>();
            ContainValue.partPerson.add(tempFriend);
        }
        tempCheckedFriend.addAll(ContainValue.partPerson);
        ContainValue.partPerson.remove(ContainValue.partPerson.size() - 1);
        KLog.i(tempCheckedFriend.size());
        mPresenter.init(ContainValue.partPerson);
    }

    @Override
    protected void setupActivityComponent() {
        DaggerAddPersonComponent
                .builder()
                .appComponent(((AppConfig) getApplication()).getApplicationComponent())
                .addPersonModule(new AddPersonModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void setPresenter(AddPersonContract.AddPersonContractPresenter presenter) {
        mPresenter = (AddPersonPresenter) presenter;
    }

    @Override
    public void showProgressDialog() {
        progressDialog.show();
    }

    @Override
    public void closeProgressDialog() {
        progressDialog.hide();
    }

    /**
     * 从网络拉取的联系人的集合处理完的了的数据的回调，会把这些数据直接显示在recycleview上面
     *
     * @param list
     */
    @Override
    public void groupMemberBack(ArrayList<Friend> list) {
        toolbar.getMenu().getItem(0).setTitle("全选");
        currentAdapterList = list;
        groupMemberAdapter = new GroupMemberAdapter(list);
        if (getIntent().getStringExtra("title").equals("添加群成员") || "发起群聊".equals(getIntent().getStringExtra("title"))) {
            groupMemberAdapter.setCanDelet(false);
        }
        groupMemberAdapter.setOncheckChange(this);
        recycerViewJiagou.setAdapter(groupMemberAdapter);
    }

    /**
     * 对其他组的成员进行操作时进行更新
     *
     * @param list  选中状态
     * @param alist 选中人数的总数
     */
    @Override
    public void onCheckedPersonChange(ArrayList<MultiItemEntity> list, ArrayList<Friend> alist) {
        KLog.i("刷新刷新onCheckedPersonChange。。。。。。。。。。。。。。");
//        handler.sendEmptyMessageDelayed(0, 500);
//        if (groupMemberAdapter != null) {
//            groupMemberAdapter.setNewData(list);
//        }
        checkPersonAdapter.setNewData(list);
        KLog.i(alist.size());
        if (alist.size() == 0) {
            tvCount.setText("确定");
            tvCount.setClickable(false);
            tvCount.setBackground(getResources().getDrawable(R.drawable.coonfirm_zero_color_background));
        } else {
            tvCount.setText("确定(" + alist.size() + ")");
            tvCount.setClickable(true);
            tvCount.setBackground(getResources().getDrawable(R.drawable.main_color_background));
        }
    }

    /**
     * 对好友进行操作时进行更新
     *
     * @param list
     * @param alist
     */
    @Override
    public void onCheckedFriendChange(ArrayList<MultiItemEntity> list, ArrayList<Friend> alist) {
        KLog.i("刷新刷新onCheckedFriendChange。。。。。。。。。。。。。。");
//            handler.sendEmptyMessageDelayed(0, 500);
        KLog.i(alist.size());
        if (alist.size() == 0) {
            tvCount.setText("确定");
            tvCount.setClickable(false);
            tvCount.setBackground(getResources().getDrawable(R.drawable.coonfirm_zero_color_background));
        } else {
            tvCount.setText("确定(" + alist.size() + ")");
            tvCount.setClickable(true);
            tvCount.setBackground(getResources().getDrawable(R.drawable.main_color_background));
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            checkPersonAdapter.notifyDataSetChanged();
        }
    };

    @Override
    public void onConfirmClick(ArrayList<Friend> list) {
        Friend tempFriend = new Friend("", "-1", "", Uri.parse(""));
        tempFriend.setUserId("-1");
        if (getIntent().getStringExtra("title").equals("选择负责人")) {
            ContainValue.projectManagers = list;
            ContainValue.projectManagers.add(tempFriend);
            setResult(20);
            finish();
        } else if (getIntent().getStringExtra("title").equals("选择参与人")) {
            ContainValue.partPerson = list;
            ContainValue.partPerson.add(tempFriend);
            setResult(20);
            finish();
        } else if (getIntent().getStringExtra("title").equals("发起群聊")) {
            ContainValue.partPerson = list;
            setResult(20);
            finish();
        } else if (getIntent().getStringExtra("title").equals("添加群成员")) {
            ContainValue.partPerson = list;
            setResult(20);
            finish();
        } else {
            ContainValue.partPerson = list;
            ContainValue.partPerson.add(tempFriend);
            Intent intent = new Intent();
            try {
                intent.putExtra("key", getIntent().getStringExtra("key"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            setResult(20, intent);
            finish();
        }
    }


    //适配器里的子条目的点击回调
    @Override
    public void onItemClick(PersonItem item) {
        if (item.type.equals("qunzu")) {
            jiagou.setVisibility(View.VISIBLE);
            if (groupMemberAdapter != null) {
                groupMemberAdapter.setNewData(new ArrayList<Friend>());
            }
            Map<String, String> map = new HashMap<>();
            map.put("pageSize", "500");
            map.put("pageNum", "1");
            mPresenter.getGroupMember(item.group.getId() + "", map);
        }

        if (item.type.equals("zuzhi")) {
            if (item.node.getId() == -1) {
                Intent intent = new Intent(this, FrameworkActivity.class);
                intent.putExtra("flag", "checkPerson");
                startActivityForResult(intent, 1);
            } else {
                jiagou.setVisibility(View.VISIBLE);
                if (groupMemberAdapter != null) {
                    groupMemberAdapter.setNewData(new ArrayList<Friend>());
                }
                Map<String, String> map = new HashMap<>();
                map.put("pageSize", "500");
                map.put("pageNum", "1");
                mPresenter.getNodeMember(item.node.getId() + "", map);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1 && resultCode == RESULT_OK) {
            jiagou.setVisibility(View.VISIBLE);
            if (groupMemberAdapter != null) {
                groupMemberAdapter.setNewData(new ArrayList<Friend>());
            }
            Map<String, String> map = new HashMap<>();
            map.put("pageSize", "500");
            map.put("pageNum", "1");
            mPresenter.getNodeMember(data.getIntExtra("nodeId", -1) + "", map);
        }
    }

    @Override
    public void onBackPressed() {
        if (jiagou.getVisibility() == View.VISIBLE) {
            toolbar.getMenu().getItem(0).setTitle("");
            jiagou.setVisibility(View.GONE);
            return;
        }
//        Friend tempFriend = new Friend("", "-1", "", Uri.parse(""));
//        tempFriend.setUserId("-1");
//        ContainValue.partPerson.add(tempFriend);
        ContainValue.partPerson.clear();
        ContainValue.partPerson.addAll(tempCheckedFriend);
        super.onBackPressed();
    }

    //GroupMemberAdapter的选中状态的回调
    @Override
    public void onCheckChange(Friend friend, boolean isChecked) {
        KLog.i("GroupMemberAdapter的选中状态在AddPersonActivity中的回调");
        mPresenter.onCheckChange(friend, isChecked);
    }

    //
    @OnClick(R.id.tv_count)
    public void onViewClicked() {
        mPresenter.onConfirmClick();
    }

    @Override
    public void onPersonCheckChange(Friend friend, boolean isChecked) {
        mPresenter.onFriendCheckChange(friend, isChecked);
    }

    @Override
    public void onContactItemOpen() {
        for (int i = 0; i < checkPersonAdapter.getData().size(); i++) {
            if (checkPersonAdapter.getData().get(i).getItemType() == TYPE_PERSON) {
                PersonItem temp = (PersonItem) checkPersonAdapter.getData().get(i);
                if (!temp.type.equals("contact")) {
                    continue;
                }
                for (int j = 0; j < ContainValue.partPerson.size(); j++) {
                    if (((PersonItem) checkPersonAdapter.getData().get(i)).freind.getUserId().equals(ContainValue.partPerson.get(j).getUserId())) {
                        KLog.i("给" + ((PersonItem) checkPersonAdapter.getData().get(i)).freind.getNickname() + "加上已经选中的标记");
                        ((PersonItem) checkPersonAdapter.getData().get(i)).freind.setChecked(true);
                    }
                }
            }
            if (getIntent().getStringExtra("title").equals("添加群成员")) {
                if (ContainValue.userList.get(i).getItemType() == CheckPersonAdapter.TYPE_PERSON) {
                    final PersonItem lv1 = (PersonItem) ContainValue.userList.get(i);
                    for (int j = 0; j < ContainValue.currentGroupMember.size(); j++) {
                        if ("contact".equals(lv1.type)) {
                            if (ContainValue.currentGroupMember.get(j).getUserId().equals(lv1.freind.getUserId())) {
                                KLog.i("这个不能选");
                                ((PersonItem) ContainValue.userList.get(i)).freind.setCanCheck(false);
                                break;
                            } else {
                                KLog.i("这个能选");
                                ((PersonItem) ContainValue.userList.get(i)).freind.setCanCheck(true);
                            }
                        }
                    }
                }
            }
            if (getIntent().getStringExtra("title").equals("发起群聊")) {
                if (ContainValue.userList.get(i).getItemType() == CheckPersonAdapter.TYPE_PERSON) {
                    final PersonItem lv1 = (PersonItem) ContainValue.userList.get(i);
                    if ("contact".equals(lv1.type)) {
                        if ((ContainValue.userLogin.getData().getUserId() + "").equals(lv1.freind.getUserId())) {
                            KLog.i("这个不能选");
                            ((PersonItem) ContainValue.userList.get(i)).freind.setCanCheck(false);
                            break;
                        } else {
                            KLog.i("这个能选");
                            ((PersonItem) ContainValue.userList.get(i)).freind.setCanCheck(true);
                        }
                    }
                }
            }
        }
        checkPersonAdapter.notifyDataSetChanged();
    }

    @Override
    public void handlerFriendCheckChange(Friend friend, boolean isChecked) {
        for (int i = 0; i < checkPersonAdapter.getData().size(); i++) {
            if (checkPersonAdapter.getData().get(i).getItemType() == TYPE_PERSON) {
                PersonItem temp = (PersonItem) checkPersonAdapter.getData().get(i);
                if (!temp.type.equals("contact")) {
                    continue;
                }
                if (((PersonItem) checkPersonAdapter.getData().get(i)).freind.getUserId().equals(friend.getUserId())) {
                    KLog.i("处理联系人列表的是否选中");
                    ((PersonItem) checkPersonAdapter.getData().get(i)).freind.setChecked(isChecked);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
    }
}